from rest_framework import serializers
from .models import Area
from user.models import Address,User
import re
class AreasSearializer(serializers.ModelSerializer):

    class Meta:
        model = Area
        fields = ('id','name')


class AreasAddSerializer(serializers.ModelSerializer):
    # 模型类的字段名为province_id，序列化器继承模型类时默认自带一个PrimaryKeyRelatedField字段，
    # 反序列化接收时想以自带的PrimaryKeyRelatedField接收，但是序列化返回时需要以province字段字符串返回，
    # 在序列化器定义关联对象字段province又和和模型类的外键名字不相同，关联不起来，返回时validated_data没有这个province字段
    province_id = serializers.IntegerField()
    city_id = serializers.IntegerField()
    district_id = serializers.IntegerField()
    province = serializers.StringRelatedField(label='省')
    city = serializers.StringRelatedField(label='市')
    district = serializers.StringRelatedField(label='区')

    class Meta:
        model = Address
        fields = ('id','title','receiver','place','mobile','tel','email','province_id','city_id','district_id','province','city','district')
        # 只能用作反序列化，序列化器继承模型类就是有queryset参数,但是设置了也能序列化返回的？？
        write_only_fields = ('province_id','city_id','district_id')
        read_only_fields = ('province','city','district')

    def validate(self, attrs):
        if not re.match(r'1[3-9]\d+',attrs['mobile']):
            raise serializers.ValidationError('手机号格式错误')
        # count = self.context['request'].user.user_address.count()
        count = Address.objects.filter(is_delete=False,user=self.context['request'].user).count()
        print(count)
        if count > 4:
            raise serializers.ValidationError('增加地址超过限值')
        print(attrs)
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['user'] = user
        print(validated_data)
        address = super().create(validated_data)
        # 返回保存好的地址对象
        return address


# serializers.Serializer没自带update方法
class AreasTitleSerializer(serializers.ModelSerializer):
    # id = serializers.IntegerField(label='id',min_value=1)
    # title = serializers.CharField(max_length=20,label='地址标题')

    class Meta:
        model = Address
        fields = ['title']

    # def update(self, instance, validated_data):
    #
    #     instance.title = validated_data['title']
    #     instance.save()
    #
    #     return instance


class AreasStatusSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','default_address']


    # def update(self, instance, validated_data):
    #     user = self.request.user
    #     user.default_address = instance
    #     user.save()
    #     return user
















